<template>
  <div class="app-container">
    <div class="app-container-inner">
      <div v-if="userStore.utype == 2">
        <div style="margin-bottom: 2%; margin-left: 2%">
          <el-form :inline="true" :model="queryForm" class="demo-form-inline">
            <el-form-item label="姓名">
              <el-input v-model="queryForm.name" clearable />
            </el-form-item>
            <el-form-item label="学号">
              <el-input v-model="queryForm.num" clearable />
            </el-form-item>
            <el-form-item label="身份">
              <el-select v-model="queryForm.status" placeholder="选择身份" multiple clearable>
                <el-option label="本科生" value="1" />
                <el-option label="硕士生" value="2" />
                <el-option label="博士生" value="3" />
                <el-option label="教职工" value="4" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="query">查询(满足任一条件都将查询出来)</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="sendActivity">发送公告</el-button>
            </el-form-item>
            <br />
            <el-form-item label="政治面貌">
              <el-select v-model="queryForm.outlook" placeholder="选择政治面貌" multiple clearable>
                <el-option label="申请入党" value="1" />
                <el-option label="入党积极分子" value="2" />
                <el-option label="入党发展对象" value="3" />
                <el-option label="预备党员接收" value="4" />
                <el-option label="预备党员考察" value="5" />
              </el-select>
            </el-form-item>
            <el-form-item label="当前阶段">
              <el-select v-model="queryForm.period" placeholder="选择当前阶段" multiple clearable>
                <el-option label="递交入党申请书" value="1" />
                <el-option label="党组织派人谈话" value="2" />
                <el-option label="团推优或党员推荐" value="3" />
                <el-option label="党支部会议通过" value="4" />
                <el-option label="上级党委备案" value="5" />
                <el-option label="指定培养联系人" value="6" />
                <el-option label="完成一年培养考察" value="7" />
                <el-option label="发展对象考核推优" value="8" />
                <el-option label="群众座谈会" value="9" />
                <el-option label="确定发展对象" value="10" />
                <el-option label="上级党委备案" value="11" />
                <el-option label="确定入党介绍人" value="12" />
                <el-option label="政治审查" value="13" />
                <el-option label="党校集中培训" value="14" />
                <el-option label="支部委员会审查" value="15" />
                <el-option label="上级党委预审" value="16" />
                <el-option label="填写入党申请书" value="17" />
                <el-option label="支部大会讨论" value="18" />
                <el-option label="上级党委谈话" value="19" />
                <el-option label="上级党委审批" value="20" />
                <el-option label="编入党支部" value="21" />
                <el-option label="入党宣誓" value="22" />
                <el-option label="继续教育考察" value="23" />
                <el-option label="提出转正申请" value="24" />
                <el-option label="支部大会讨论" value="25" />
                <el-option label="上级党委审批" value="26" />
                <el-option label="材料归档" value="27" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-popconfirm title="确定要删除吗?" @confirm="batchDelete">
                <template #reference>
                  <el-button type="danger">批量删除</el-button>
                </template>
              </el-popconfirm>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="batchEdit">批量进入下一阶段</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="batchSend">批量发送信息</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          :row-key="getRowKeys"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" :reserve-selection="true" width="30" />
          <el-table-column property="name" label="姓名" width="70" />
          <el-table-column property="num" label="学号/工号" width="110" />
          <el-table-column property="status" label="身份" width="80" />
          <el-table-column property="phone" label="手机号" width="140" />
          <el-table-column property="branch_name" label="所在党支部" width="140" />
          <el-table-column property="period" label="当前阶段" width="150" />
          <el-table-column property="outlook" label="政治面貌" width="120" />
          <el-table-column property="create_date" label="创建时间" width="140" />
          <el-table-column property="operation" label="操作">
            <template #default="scope">
              <el-button
                v-if="scope.row.period != '材料归档'"
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                >进入下一阶段</el-button
              >
              <el-popconfirm
                title="确定要删除该名党员吗?"
                @confirm="handleDelete(scope.$index, scope.row)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
              <el-button size="small" type="success" @click="sendNotice(scope.$index, scope.row)"
                >发送通知</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!--
        <el-pagination
          background
          layout="prev, pager, next"
          style="margin-left: 65%; margin-top: 2%"
          small
          :total="total"
          @current-change="handelCurrentChange"
          v-model:current-page="currentPage"
        />
        -->
        <div>
          <el-dialog v-model="VisEditInfo" title="进入下一阶段" width="30%">
            <div class="m-4">
              <p>修改时间</p>
              <el-date-picker
                v-model="ruleForm.exchangeDateTime"
                type="datetime"
                placeholder="选择党员身份变化时间"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="x"
              />
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="VisEditInfo = false">取消</el-button>
                <el-button type="primary" @click="editInfo">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        <div>
          <el-dialog v-model="VisBatchEdit" title="批量进入下一阶段" width="30%">
            <div class="m-4">
              <p>修改时间</p>
              <el-date-picker
                v-model="ruleForm.exchangeDateTime"
                type="datetime"
                placeholder="选择党员身份变化时间"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="x"
              />
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="VisBatchEdit = false">取消</el-button>
                <el-button type="primary" @click="batchEditPerson">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        <div>
          <el-dialog v-model="VisSendNotice" title="发送通知" width="80%">
            <div style="margin-bottom: 2%">
              <el-input v-model="noticeTitle" placeholder="通知标题">
                <template #prepend>标题</template>
              </el-input>
            </div>
            <Wangeditor v-model="editorContent" style="margin-bottom: 2%"></Wangeditor>
            <el-button type="primary" @click="send">发送</el-button>
            <el-button @click="VisSendNotice = false">取消</el-button>
          </el-dialog>
        </div>
        <div>
          <el-dialog v-model="VisNotice" title="批量发送通知" width="80%">
            <div style="margin-bottom: 2%">
              <el-input v-model="noticeTitle" placeholder="通知标题">
                <template #prepend>标题</template>
              </el-input>
            </div>
            <Wangeditor v-model="editorContent" style="margin-bottom: 2%"></Wangeditor>
            <el-button type="primary" @click="batchSendNotice">发送</el-button>
            <el-button @click="VisNotice = false">取消</el-button>
          </el-dialog>
        </div>
        <div>
          <el-dialog v-model="Visible" title="发送公告" width="80%">
            <div style="margin-bottom: 2%">
              <el-input v-model="activityTitle" placeholder="公告标题">
                <template #prepend>标题</template>
              </el-input>
            </div>
            <Wangeditor v-model="editorContent" style="margin-bottom: 2%"></Wangeditor>
            <el-button type="primary" @click="sendAct">发送</el-button>
            <el-button @click="Visible = false">取消</el-button>
          </el-dialog></div
        >
      </div>
      <div v-else>
        <Error></Error>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="comprehensive">
  import { ref, onMounted, onUnmounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import watermark from '@/utils/watermark.js'
  import { Cloud } from 'laf-client-sdk'
  import { getPartyMember, getAccountID } from '@/lafSdkCollection/getPartyMember'
  import { getSettingList } from '@/lafSdkCollection/getSettingInfo'
  import Wangeditor from '../../components/WangEdior/index.vue'
  import { useUserStore } from '@/store/modules/user'
  import Error from '@/views/error/404.vue'
  const APPID = 'su75ks' // Laf 应用 appid
  const cloud = new Cloud({
    baseUrl: `https://${APPID}.laf.run`,
    getAccessToken: () => userStore.token,
  })
  const userStore = useUserStore()
  const loading = ref(true)
  const multipleTableRef = ref()
  const select_order_number = ref() //表格select选中的条数
  const select_orderId = ref([]) //表格select复选框选中的id
  const select_order_num = ref([]) //表格select复选框选中的num
  const select_order_period = ref([])
  const select_order_outlook = ref([])
  const multipleSelection = ref([])
  const editorContent = ref('') //富文本编辑器内容，就是一段html代码
  const activityTitle = ref('')
  const settingStatus = ref()
  const settingOutlook = ref()
  const settingPeriod = ref()
  const getSetting = async () => {
    const { status, outlook, period } = await getSettingList()
    settingStatus.value = status
    settingOutlook.value = outlook
    settingPeriod.value = period
  }
  //选中的list
  const getRowKeys = (row) => {
    //记录每行的key值
    return row.id
  }
  //当表格选择项发生变化时会触发该事件
  const handleSelectionChange = (val) => {
    // 解决来回切换页面，也无法清除上次选中情况
    multipleSelection.value = val
    select_order_number.value = multipleSelection.value.length
    select_orderId.value = []
    select_order_num.value = []
    select_order_outlook.value = []
    select_order_period.value = []
    if (val) {
      undefined
      val.forEach((row) => {
        undefined
        if (row) {
          undefined
          select_orderId.value.push(row.id)
          select_order_num.value.push(row.num)
          select_order_outlook.value.push(row.outlook)
          select_order_period.value.push(row.period)
        }
      })
    }
  }
  const batchDelete = async () => {
    if (select_order_num.value.length == 0) {
      ElMessage('请先选择')
      return
    }
    let t = select_order_number.value
    for (let i = 0; i < t; i++) {
      const data = {
        num: select_order_num.value[i],
      }
      const res = await cloud.invoke('deleteAccount', data)
      if (t == 1 && res.code == 200) {
        ElMessage(res.message)
      } else if (t == 1 && res.code == 404) {
        ElMessage(res.error)
      }
    }
    PartyMember()
  }
  const batchEdit = () => {
    if (select_order_num.value.length == 0) {
      ElMessage('请先选择')
      return
    }
    VisBatchEdit.value = true
  }
  const batchEditPerson = async () => {
    let size = select_order_number.value
    let flag = true
    const conOutlook = select_order_outlook.value[0]
    const conPeriod = select_order_period.value[0]
    for (let i = 0; i < size; i++) {
      if (
        select_order_outlook.value[i] != conOutlook ||
        select_order_period.value[i] != conPeriod
      ) {
        flag = false
        break
      }
    }
    if (!flag) {
      ElMessage('必须选择处于一样阶段的党员通知，才能批量修改')
      return
    }
    for (let i = 0; i < size; i++) {
      const data = {
        num: select_order_num.value[i],
        time: ruleForm.value.exchangeDateTime,
        name: userStore.userInfo.name,
      }
      const res = await cloud.invoke('changeMember', data)
      if (res.code == 404) {
        ElMessage(res.error)
        break
      }
    }
    ElMessage('修改成功')
    VisBatchEdit.value = false
    PartyMember()
  }
  const batchSend = () => {
    if (select_order_num.value.length == 0) {
      ElMessage('请先选择')
      return
    }
    console.log(select_order_num.value)
    VisNotice.value = true
  }
  const VisNotice = ref(false)
  const batchSendNotice = async () => {
    let size = select_order_number.value
    if (size == 0) {
      ElMessage('请先选择')
      return
    }
    for (let i = 0; i < size; i++) {
      let tmp = await cloud.invoke('curd_op', {
        collection: 'Account_Inf',
        operation: 'get',
        data: {
          where: {
            num: select_order_num.value[i],
          },
        },
      })
      let receiver_id = tmp.data[0]._id
      let data = {
        sender_id: userStore._id,
        utype: 2,
        title: noticeTitle.value,
        content: editorContent.value,
        receiver_id: receiver_id,
      }
      let res = await cloud.invoke('send_message', data)
      if (i == size - 1 && res.code == 201) {
        ElMessage(res.msg)
        VisNotice.value = false
      } else if (i == 0 && res.code == 400) {
        ElMessage(res.error)
      }
    }
  }
  const VisEditInfo = ref(false)
  const Periodoptions = [
    {
      value: '1',
      label: '递交入党申请书',
    },
    {
      value: '2',
      label: '党组织派人谈话',
    },
    {
      value: '3',
      label: '团推优或党员推荐',
    },
    {
      value: '4',
      label: '党支部会议通过',
    },
    {
      value: '5',
      label: '上级党委备案',
    },
    {
      value: '6',
      label: '指定培养联系人',
    },
    {
      value: '7',
      label: '完成一年培养考察',
    },
    {
      value: '8',
      label: '发展对象考核推优',
    },
    {
      value: '9',
      label: '群众座谈会',
    },
    {
      value: '10',
      label: '确定发展对象',
    },
    {
      value: '11',
      label: '上级党委备案',
    },
    {
      value: '12',
      label: '确定入党介绍人',
    },
    {
      value: '13',
      label: '政治审查',
    },
    {
      value: '14',
      label: '党校集中培训',
    },
    {
      value: '15',
      label: '支部委员会审查',
    },
    {
      value: '16',
      label: '上级党委备案',
    },
    {
      value: '17',
      label: '填写入党申请书',
    },
    {
      value: '18',
      label: '支部大会讨论',
    },
    {
      value: '19',
      label: '上级党委谈话',
    },
    {
      value: '20',
      label: '上级党委审批',
    },
    {
      value: '21',
      label: '编入党支部',
    },
    {
      value: '22',
      label: '入党宣誓',
    },
    {
      value: '23',
      label: '继续教育考察',
    },
    {
      value: '24',
      label: '提出转正申请',
    },
    {
      value: '25',
      label: '支部大会讨论',
    },
    {
      value: '26',
      label: '上级党委审批',
    },
    {
      value: '27',
      label: '材料归档',
    },
  ]
  const Outlookoptions = [
    {
      value: '1',
      label: '申请入党',
    },
    {
      value: '2',
      label: '入党积极分子',
    },
    {
      value: '3',
      label: '入党发展对象',
    },
    {
      value: '4',
      label: '预备党员接收',
    },
    {
      value: '5',
      label: '预备党员考核',
    },
  ]
  const tableData = ref([])
  const total = ref(0)
  //const currentPage = ref(1)
  const Visible = ref(false)
  const tableDataCopy = ref([])
  /*
  const handelCurrentChange = (page) => {
    currentPage.value = page
    const index = 10 * (currentPage.value - 1)
    const nums = 10 * currentPage.value
    const tables = []
    for (let i = index; i < nums; i++) {
      if (tableDataCopy.value[i]) tables.push(tableDataCopy.value[i])
    }
    tableData.value = tables
  }
  */
  const queryForm = ref({
    name: '',
    num: '',
    status: [],
    period: [],
    outlook: [],
  })
  const query = () => {
    tableData.value = tableDataCopy.value
    if (
      queryForm.value.name == '' &&
      queryForm.value.num == '' &&
      queryForm.value.status.length == 0 &&
      queryForm.value.period.length == 0 &&
      queryForm.value.outlook.length == 0
    ) {
      ElMessage('请先选择搜索条件')
      return
    }
    const judge = {
      name: queryForm.value.name == '' ? false : true,
      num: queryForm.value.num == '' ? false : true,
      status: queryForm.value.status.length == 0 ? false : true,
      period: queryForm.value.period.length == 0 ? false : true,
      outlook: queryForm.value.outlook.length == 0 ? false : true,
    }
    const searchData = []
    if (judge.name) {
      searchData.push({ name: queryForm.value.name })
    }
    if (judge.num) {
      searchData.push({ num: queryForm.value.num })
    }
    if (judge.status) {
      for (let i = 0; i < queryForm.value.status.length; i++) {
        searchData.push({ status: settingStatus.value[parseInt(queryForm.value.status[i])] })
      }
    }
    if (judge.period) {
      for (let i = 0; i < queryForm.value.period.length; i++) {
        searchData.push({ period: settingPeriod.value[parseInt(queryForm.value.period[i])] })
      }
    }
    if (judge.outlook) {
      for (let i = 0; i < queryForm.value.outlook.length; i++) {
        searchData.push({ outlook: settingOutlook.value[parseInt(queryForm.value.outlook[i])] })
      }
    }
    tableData.value = tableData.value.filter((item) => {
      let isShow = searchData.some((prop) => {
        let key = Object.keys(prop)[0]
        let value = prop[key]
        return item.hasOwnProperty(key) && item[key] === value
      })
      return isShow
    })
  }
  const sendNotice = (index, row) => {
    VisSendNotice.value = true
    num.value = row.num
  }
  const sendActivity = () => {
    Visible.value = true
  }
  const sendAct = async () => {
    const data = {
      sender_id: userStore._id,
      utype: 1,
      title: activityTitle.value,
      content: editorContent.value,
      receiver_id: '',
    }
    const res = await cloud.invoke('send_message', data)
    if (res.code == 201) {
      ElMessage(res.msg)
      Visible.value = false
    } else if (res.code == 404) {
      ElMessage(res.error)
    }
  }
  const send = async () => {
    const receiver_id = await getAccountID(num.value)
    const data = {
      sender_id: userStore._id,
      utype: 2,
      title: noticeTitle.value,
      content: editorContent.value,
      receiver_id: receiver_id.data[0]._id,
    }
    const res = await cloud.invoke('send_message', data)
    if (res.code == 201) {
      ElMessage(res.msg)
      VisSendNotice.value = false
    } else if (res.code == 400) {
      ElMessage(res.error)
    }
  }
  const noticeTitle = ref('')
  const VisBatchEdit = ref(false)
  const VisSendNotice = ref(false)
  const handleEdit = (index, row) => {
    VisEditInfo.value = true
    num.value = row.num
  }
  const num = ref('')
  const editInfo = async () => {
    const data = {
      num: num.value,
      time: ruleForm.value.exchangeDateTime,
      name: userStore.userInfo.name,
    }
    const res = await cloud.invoke('changeMember', data)
    if (res.code == 200) {
      ElMessage(res.msg)
      VisEditInfo.value = false
    } else if (res.code == 404) {
      ElMessage(res.error)
    }
    PartyMember()
  }
  const handleDelete = async (index, row) => {
    const data = {
      num: row.num,
    }
    const res = await cloud.invoke('deleteAccount', data)
    if (res.code == 200) {
      ElMessage(res.message)
    } else if (res.code == 404) {
      ElMessage(res.error)
    }
    PartyMember()
  }

  const PartyMember = async () => {
    const res = await getPartyMember(userStore._id)
    let size = res.data.length
    tableDataCopy.value = []
    total.value = size
    for (let i = 0; i < size; i++) {
      let baseTime = res.data[i].create_date
      let d = new Date(baseTime)
      let batchDate = d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日'
      tableDataCopy.value.push({
        name: res.data[i].name,
        num: res.data[i].num,
        status: settingStatus.value[parseInt(res.data[i].info.status)],
        phone: res.data[i].phone,
        branch_name: userStore.info.branch_name,
        period: settingPeriod.value[parseInt(res.data[i].info.period)],
        outlook: settingOutlook.value[parseInt(res.data[i].info.outlook)],
        create_date: batchDate,
      })
    }
    tableData.value = tableDataCopy.value
  }

  const ruleForm = ref({
    //outlook: '',
    //period: '',
    exchangeDateTime: 0, //就是直接时间戳
  })

  const setWaterMark = () => {
    //添加水印
    watermark.set(userStore.info.branch_name, userStore.num)
    //移除水印,传 null 移除水印
    //watermark.close()
  }
  onUnmounted(async () => {
    watermark.close(null)
  })
  onMounted(async () => {
    setWaterMark()
    await getSetting()
    await PartyMember()
    setTimeout(() => {
      loading.value = false
    }, 500)
  })
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }
  .app-container {
    flex: 1;
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
